package com.unis.service.znzf.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.unis.common.enums.QqlxEnum;
import com.unis.common.exception.app.AppRuntimeException;
import com.unis.common.secure.authc.UserInfo;
import com.unis.common.util.TemplateUtil;
import com.unis.common.util.TimeUtil;
import com.unis.dto.ResultDto;
import com.unis.mapper.znzf.SfMxQqMapper;
import com.unis.mapper.znzf.SfZtQqMapper;
import com.unis.model.zhxx.TbJdzjfxSfZh;
import com.unis.model.znzf.SfMxQq;
import com.unis.model.znzf.SfQzhQq;
import com.unis.pojo.znzf.ReqModel;
import com.unis.service.impl.BaseServiceImpl;
import com.unis.service.zhxx.TbJdzjfxSfZhService;
import com.unis.service.znzf.*;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/**
 * <pre>
 * @see SfMxQqService
 * </pre>
 *
 * @author xuk
 * @version 1.0
 * @since 2019-03-04
 */
@Service("sfMxQqService")
public class SfMxQqServiceImpl extends BaseServiceImpl implements SfMxQqService {
    private static final Logger logger = LoggerFactory.getLogger(SfMxQqServiceImpl.class);
    @Autowired
    private SfMxQqMapper sfMxQqMapper;
    @Autowired
    private ZnzfQueueService znzfQueueService;
    @Autowired
    private ZnzfService znzfService;
    @Autowired
    private JltService jltService;
    @Autowired
    private SfZtQqMapper sfZtQqMapper;
    @Autowired
    private SfQzhQqService sfQzhQqService;
    @Autowired
    private MxQqGlService mxQqGlService;
    @Autowired
    private TbJdzjfxSfZhService tbJdzjfxSfZhService;

    /**
     * @see SfMxQqService#insert(SfMxQq sfMxQq)
     */
    @Override
    public int insert(SfMxQq sfMxQq) throws Exception {
        if (sfMxQq != null) {
            sfMxQq.setPk(TemplateUtil.genUUID());
            //menu.setPk(getPk("seqName","jgdm","A"));
            return sfMxQqMapper.insertSelective(sfMxQq);
        } else {
            logger.error("SfMxQqServiceImpl.insert时sfMxQq数据为空。");
            throw new AppRuntimeException("SfMxQqServiceImpl.insert时sfMxQq数据为空。");
        }
    }

    @Override
    public int insertSfMx(ReqModel reqModel) throws Exception {
        int resultNumber = 0;
        Map bean = null;
        if (reqModel != null && reqModel.getBean() != null
                && !reqModel.getBean().isEmpty() && reqModel.getBean().size() > 0) {
            List<Map> list;
            UserInfo user = this.getUserInfo();
            Date nowDate = this.getDbDate();
            for (Map<String, String> map : reqModel.getBean()) {
                list = new ArrayList<>();
                if (map == null || map.isEmpty() || map.size() < 1) {
                    continue;
                }
                bean = new HashMap();
                bean.put("pk", TemplateUtil.genUUID());
                bean.put("ztpk", TemplateUtil.genUUID());
                bean.put("lrdwdm", user.getJgdm());
                bean.put("lrdwmc", user.getJgmc());
                bean.put("lrrxm", user.getXm());
                bean.put("lrrjh", user.getJh());
//                bean.put("jjdpk", reqModel.getJjdPk());
                String jjdPk = map.get("jjdPk");
                bean.put("jjdpk", jjdPk);
                bean.put("reason", reqModel.getSy());
                bean.put("subjecttype", StringUtils.isNotBlank(map.get("subjecttype")) ? Short.parseShort(map.get("subjecttype")) : 1);

                bean.put("paycode", map.get("paycode"));
                bean.put("payname", map.get("payname"));

                String zh = StringUtils.isNotBlank(map.get("accnumber")) ? map.get("accnumber") : "";
                bean.put("accnumber", zh);

                bean.put("starttime", StringUtils.isNotBlank(map.get("starttime")) ? TimeUtil.strToDate(map.get("starttime"), "yyyy-MM-dd") : DateUtils.addDays(nowDate, -1));
                bean.put("expiretime", StringUtils.isNotBlank(map.get("expiretime")) ? TimeUtil.strToDate(map.get("expiretime"), "yyyy-MM-dd") : nowDate);

                //报文生成所需字段
                bean.put("bankname", map.get("payname"));
                bean.put("bankcode", map.get("paycode"));
                bean.put("cardnumber", zh);
                //bean.put("accountname",reqModel.getShr());
                bean.put("zhlx", StringUtils.isNotBlank(map.get("zzfs")) ? map.get("zzfs") : "支付账号");

                //增加转账时间
                bean.put("zzsj", StringUtils.isNotBlank(map.get("zzsj")) ? TimeUtil.strToDate(map.get("zzsj"), null) : null);

                String mongoPk = "";
                Example example = new Example(SfMxQq.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("yxx", 1);
                criteria.andEqualTo("jjdpk", jjdPk);
                criteria.andEqualTo("lrdwdm", user.getJgdm());
                criteria.andEqualTo("paycode", bean.get("paycode"));
                criteria.andEqualTo("accnumber", bean.get("accnumber"));
                List<SfMxQq> qqList = this.queryListByExample(example);
                if (qqList != null && !qqList.isEmpty()) {
                    mongoPk = qqList.get(0).getFlws();
                } else {
                    mongoPk = znzfService.insertMongo("sf", "cx", bean);
                }
                bean.put("flws", mongoPk);

                bean.put("nlevel", 1);
                bean.put("sertype", new Short("2"));
                bean.put("parentpk", reqModel.getParentpk());
                bean.put("parentzh", reqModel.getParentzh());
                bean.put("iszcygzs", reqModel.getIszcygzs());
                list.add(bean);
                List<Map> queueList = new ArrayList();
                String qzhpk= TemplateUtil.genUUID();
                if (zh.endsWith("@wx.tenpay.com")) {
                	bean.put("qzhpk",qzhpk);
                }
                jltService.checkJltAndInsert(bean);
                bean.put("kssj", bean.get("starttime"));
                bean.put("jssj", bean.get("expiretime"));
                bean.put("glpk", TemplateUtil.genUUID());
                queueList.add(bean);
                sfMxQqMapper.insertBatch(list);
                mxQqGlService.insertBatch(queueList);
                znzfQueueService.insertBatchMx(queueList, QqlxEnum.sfQqlxMxcx.getKey(), (short) 1);

                resultNumber = sfZtQqMapper.insertBatchZt(list);
                znzfQueueService.insertBatchZt(list, QqlxEnum.sfQqlxZtcx.getKey(), (short) 1);
                if (zh.endsWith("@wx.tenpay.com")) {
                    SfQzhQq sfQzhQq = new SfQzhQq();
                    sfQzhQq.setPk(qzhpk);
                    sfQzhQq.setJjdpk(jjdPk);
                    sfQzhQq.setSubjecttype((short) 1);
                    sfQzhQq.setPaycode(bean.get("bankcode").toString());
                    sfQzhQq.setPayname(bean.get("bankname").toString());
                    sfQzhQq.setAcctype("04");
                    sfQzhQq.setAccnumber(zh);
                    sfQzhQq.setAccountname("");
                    sfQzhQq.setAccountype("");
                    sfQzhQq.setReason(reqModel.getSy());
                    sfQzhQq.setRemark("");
                    sfQzhQq.setLrdwdm(user.getJgdm());
                    sfQzhQq.setLrdwmc(user.getJgmc());
                    sfQzhQq.setLrrxm(user.getXm());
                    sfQzhQq.setLrrjh(user.getJh());
                    sfQzhQq.setRksj(new Date());
                    sfQzhQq.setFlws(mongoPk);
                    sfQzhQq.setZzsj((Date) bean.get("zzsj"));
                    sfQzhQq.setNlevel((short) 0);
                    sfQzhQq.setFxbs((short) 1);
                    resultNumber = sfQzhQqService.insert(sfQzhQq);
                    List sfqzhList = new ArrayList(1);
                    bean.put("pk", sfQzhQq.getPk());
                    sfqzhList.add(bean);
                    znzfQueueService.insertBatch(sfqzhList, QqlxEnum.sfQqlxQzhcx.getKey(), (short) 1);
                }
                
                TbJdzjfxSfZh tbJdzjfxSfZh = tbJdzjfxSfZhService.queryTbJdzjfxSfZhByPrimaryKey(jjdPk);
                tbJdzjfxSfZh.setCj("1");
                tbJdzjfxSfZh.setFxbs((short) 2);
                tbJdzjfxSfZh.setFxsj(new Date());
                tbJdzjfxSfZhService.updateByPrimaryKey(tbJdzjfxSfZh);

            }
        }
        return resultNumber;
    }

    /**
     * 复制map对象
     *
     * @param paramsMap 被拷贝对象
     * @param resultMap 拷贝后的对象
     * @explain 将paramsMap中的键值对全部拷贝到resultMap中；
     * paramsMap中的内容不会影响到resultMap（深拷贝）
     */
    private static void mapCopy(Map paramsMap, Map resultMap) {
        if (resultMap == null) resultMap = new HashMap();
        if (paramsMap == null) return;

        Iterator it = paramsMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            Object key = entry.getKey();
            resultMap.put(key, paramsMap.get(key) != null ? paramsMap.get(key) : "");

        }
    }

    /**
     * @see SfMxQqService#delete(String pk)
     */
    @Override
    public int delete(String pk) throws Exception {
        if (StringUtils.isBlank(pk)) {
            logger.error("SfMxQqServiceImpl.delete时pk为空。");
            throw new AppRuntimeException("SfMxQqServiceImpl.delete时pk为空。");
        } else {
            return sfMxQqMapper.deleteByPrimaryKey(pk);
        }
    }

    /**
     * @see SfMxQqService#updateByPrimaryKey(SfMxQq sfMxQq)
     */
    @Override
    public int updateByPrimaryKey(SfMxQq sfMxQq) throws Exception {
        if (sfMxQq != null) {
            if (StringUtils.isBlank(sfMxQq.getPk())) {
                logger.error("SfMxQqServiceImpl.updateByPrimaryKey时sfMxQq.Pk为空。");
                throw new AppRuntimeException("SfMxQqServiceImpl.updateByPrimaryKey时sfMxQq.Pk为空。");
            }
            return sfMxQqMapper.updateByPrimaryKeySelective(sfMxQq);
        } else {
            logger.error("SfMxQqServiceImpl.updateByPrimaryKey时sfMxQq数据为空。");
            throw new AppRuntimeException("SfMxQqServiceImpl.updateByPrimaryKey时sfMxQq数据为空。");
        }
    }

    @Override
    public int updateLevelByJlt(String jjdpk, String accnumber, int nlevel, int newNlevel, int thisNlevel) throws Exception {
        return sfMxQqMapper.updateNlevel(jjdpk, accnumber, nlevel, newNlevel, thisNlevel);
    }

    /**
     * @see SfMxQqService#querySfMxQqByPrimaryKey(String pk)
     */
    @Override
    public SfMxQq querySfMxQqByPrimaryKey(String pk) throws Exception {
        if (StringUtils.isBlank(pk)) {
            logger.error("SfMxQqServiceImpl.querySfMxQqByPrimaryKey时pk为空。");
            throw new AppRuntimeException("SfMxQqServiceImpl.querySfMxQqByPrimaryKey时pk为空。");
        } else {
            return sfMxQqMapper.selectByPrimaryKey(pk);
        }
    }


    /**
     * @see SfMxQqService#queryAsObject(SfMxQq sfMxQq)
     */
    @Override
    public SfMxQq queryAsObject(SfMxQq sfMxQq) throws Exception {
        if (sfMxQq != null) {
            return sfMxQqMapper.selectOne(sfMxQq);
        } else {
            logger.error("SfMxQqServiceImpl.queryAsObject时sfMxQq数据为空。");
            throw new AppRuntimeException("SfMxQqServiceImpl.queryAsObject时sfMxQq数据为空。");
        }
    }

    /**
     * @see SfMxQqService#queryCountByExample(Example example)
     */
    @Override
    public int queryCountByExample(Example example) throws Exception {
        if (example != null) {
            return sfMxQqMapper.selectCountByExample(example);
        } else {
            logger.error("SfMxQqServiceImpl.queryCountByExample时example数据为空。");
            throw new AppRuntimeException("SfMxQqServiceImpl.queryCountByExample时example数据为空。");
        }
    }

    /**
     * @see SfMxQqService#queryListByExample(Example example)
     */
    @Override
    public List<SfMxQq> queryListByExample(Example example) throws Exception {
        if (example != null) {
            return sfMxQqMapper.selectByExample(example);
        } else {
            logger.error("SfMxQqServiceImpl.queryListByExample时example数据为空。");
            throw new AppRuntimeException("SfMxQqServiceImpl.queryListByExample时example数据为空。");
        }
    }

    /**
     * @see SfMxQqService#queryPageInfoByExample(Example example, int pageNum, int pageSize)
     */
    @Override
    public PageInfo queryPageInfoByExample(Example example, int pageNum, int pageSize) throws Exception {
        if (example != null) {
            PageHelper.startPage(pageNum, pageSize);
            return new PageInfo(sfMxQqMapper.selectByExample(example));
        } else {
            logger.error("SfMxQqServiceImpl.queryListByExample时example数据为空。");
            throw new AppRuntimeException("SfMxQqServiceImpl.queryListByExample时example数据为空。");
        }
    }

    /**
     * @see SfMxQqService#queryListByPage(Map parmMap, int pageNum, int pageSize)
     */
    @Override
    public ResultDto queryListByPage(Map parmMap, int pageNum, int pageSize) throws Exception {
        if (parmMap != null) {
            Example example = new Example(SfMxQq.class);
            //example.setOrderByClause("rksj DESC,pk asc");设置排序
            Example.Criteria criteria = example.createCriteria();
            //criteria设置
            // = --> andEqualTo(field,value)
            // like --> andLike(field,likeValue)；likeValue 包含‘%’
            // is null --> andIsNull(field)
            // is not null --> andIsNotNull(field)
            // <> --> andNotEqualTo(field)
            // > --> andGreaterThan(field,value)
            // >= --> andGreaterThanOrEqualTo(field,value)
            // < --> andLessThan(field,value)
            // <= --> andLessThanOrEqualTo(field,value)
            // in --> andIn(field,Iterable value)
            // not in --> andNotIn(field,Iterable value)
            // between --> andBetween(field,beginValue,endValue)
            // not like --> andNotLike(field,likeValue)；likeValue 包含‘%’

            // or --> 上述方法的and 都有与之对应的or方法 eg: orEqualTo(field,value)

            //criteria.andEqualTo("yxx",1);设置yxx=1
            /**
             *此方法请根据需要修改下方条件
             */
            //此查询仅针对单表查询，若需要多表查询，尽量使用配置Mapper.xml 和Mapper.java的方式
            //生成条件中均为 and field = value
            //生成代码中，若表结构中有_等字符，生成字段可能会与实体类不同，请注意修改

            boolean flag = false;
            if (parmMap.get("pk") != null && StringUtils.isNotBlank(parmMap.get("pk").toString())) {
                criteria.andEqualTo("pk", parmMap.get("pk").toString().trim());
                flag = true;
            }
            if (parmMap.get("jjdpk") != null && StringUtils.isNotBlank(parmMap.get("jjdpk").toString())) {
                criteria.andEqualTo("jjdpk", parmMap.get("jjdpk").toString().trim());
                flag = true;
            }
            if (parmMap.get("applicationid") != null && StringUtils.isNotBlank(parmMap.get("applicationid").toString())) {
                criteria.andEqualTo("applicationid", parmMap.get("applicationid").toString().trim());
                flag = true;
            }
            if (parmMap.get("subjecttype") != null && StringUtils.isNotBlank(parmMap.get("subjecttype").toString())) {
                criteria.andEqualTo("subjecttype", parmMap.get("subjecttype").toString().trim());
                flag = true;
            }
            if (parmMap.get("paycode") != null && StringUtils.isNotBlank(parmMap.get("paycode").toString())) {
                criteria.andEqualTo("paycode", parmMap.get("paycode").toString().trim());
                flag = true;
            }
            if (parmMap.get("payname") != null && StringUtils.isNotBlank(parmMap.get("payname").toString())) {
                criteria.andEqualTo("payname", parmMap.get("payname").toString().trim());
                flag = true;
            }
            if (parmMap.get("accnumber") != null && StringUtils.isNotBlank(parmMap.get("accnumber").toString())) {
                criteria.andEqualTo("accnumber", parmMap.get("accnumber").toString().trim());
                flag = true;
            }
            if (parmMap.get("inquirymode") != null && StringUtils.isNotBlank(parmMap.get("inquirymode").toString())) {
                criteria.andEqualTo("inquirymode", parmMap.get("inquirymode").toString().trim());
                flag = true;
            }
            if (parmMap.get("starttime") != null && StringUtils.isNotBlank(parmMap.get("starttime").toString())) {
                criteria.andEqualTo("starttime", parmMap.get("starttime").toString().trim());
                flag = true;
            }
            if (parmMap.get("expiretime") != null && StringUtils.isNotBlank(parmMap.get("expiretime").toString())) {
                criteria.andEqualTo("expiretime", parmMap.get("expiretime").toString().trim());
                flag = true;
            }
            if (parmMap.get("reason") != null && StringUtils.isNotBlank(parmMap.get("reason").toString())) {
                criteria.andEqualTo("reason", parmMap.get("reason").toString().trim());
                flag = true;
            }
            if (parmMap.get("remark") != null && StringUtils.isNotBlank(parmMap.get("remark").toString())) {
                criteria.andEqualTo("remark", parmMap.get("remark").toString().trim());
                flag = true;
            }
            if (parmMap.get("lrdwdm") != null && StringUtils.isNotBlank(parmMap.get("lrdwdm").toString())) {
                criteria.andEqualTo("lrdwdm", parmMap.get("lrdwdm").toString().trim());
                flag = true;
            }
            if (parmMap.get("lrdwmc") != null && StringUtils.isNotBlank(parmMap.get("lrdwmc").toString())) {
                criteria.andEqualTo("lrdwmc", parmMap.get("lrdwmc").toString().trim());
                flag = true;
            }
            if (parmMap.get("lrrxm") != null && StringUtils.isNotBlank(parmMap.get("lrrxm").toString())) {
                criteria.andEqualTo("lrrxm", parmMap.get("lrrxm").toString().trim());
                flag = true;
            }
            if (parmMap.get("lrrjh") != null && StringUtils.isNotBlank(parmMap.get("lrrjh").toString())) {
                criteria.andEqualTo("lrrjh", parmMap.get("lrrjh").toString().trim());
                flag = true;
            }
            if (parmMap.get("rksj") != null && StringUtils.isNotBlank(parmMap.get("rksj").toString())) {
                criteria.andEqualTo("rksj", parmMap.get("rksj").toString().trim());
                flag = true;
            }
            if (parmMap.get("yxx") != null && StringUtils.isNotBlank(parmMap.get("yxx").toString())) {
                criteria.andEqualTo("yxx", parmMap.get("yxx").toString().trim());
                flag = true;
            }
            if (parmMap.get("reqflag") != null && StringUtils.isNotBlank(parmMap.get("reqflag").toString())) {
                criteria.andEqualTo("reqflag", parmMap.get("reqflag").toString().trim());
                flag = true;
            }
            if (parmMap.get("reqdate") != null && StringUtils.isNotBlank(parmMap.get("reqdate").toString())) {
                criteria.andEqualTo("reqdate", parmMap.get("reqdate").toString().trim());
                flag = true;
            }
            if (parmMap.get("reqcount") != null && StringUtils.isNotBlank(parmMap.get("reqcount").toString())) {
                criteria.andEqualTo("reqcount", parmMap.get("reqcount").toString().trim());
                flag = true;
            }
            if (parmMap.get("resflag") != null && StringUtils.isNotBlank(parmMap.get("resflag").toString())) {
                criteria.andEqualTo("resflag", parmMap.get("resflag").toString().trim());
                flag = true;
            }
            if (parmMap.get("resdate") != null && StringUtils.isNotBlank(parmMap.get("resdate").toString())) {
                criteria.andEqualTo("resdate", parmMap.get("resdate").toString().trim());
                flag = true;
            }
            if (parmMap.get("resultcode") != null && StringUtils.isNotBlank(parmMap.get("resultcode").toString())) {
                criteria.andEqualTo("resultcode", parmMap.get("resultcode").toString().trim());
                flag = true;
            }
            if (parmMap.get("feedbackremark") != null && StringUtils.isNotBlank(parmMap.get("feedbackremark").toString())) {
                criteria.andEqualTo("feedbackremark", parmMap.get("feedbackremark").toString().trim());
                flag = true;
            }
            if (parmMap.get("flws") != null && StringUtils.isNotBlank(parmMap.get("flws").toString())) {
                criteria.andEqualTo("flws", parmMap.get("flws").toString().trim());
                flag = true;
            }
            //一个条件都没有的时候给一个默认条件
            if (!flag) {

            }
            PageInfo pageInfo = this.queryPageInfoByExample(example, pageNum, pageSize);
            ResultDto result = new ResultDto();
            result.setRows(pageInfo.getList());
            result.setPage(pageInfo.getPageNum());
            //result.setTotal(pageInfo.getPages());
            result.setTotal((int) pageInfo.getTotal());
            return result;
        } else {
            logger.error("SfMxQqServiceImpl.queryListByPage时parmMap数据为空。");
            throw new AppRuntimeException("SfMxQqServiceImpl.queryListByPage时parmMap数据为空。");
        }
    }
}
